package com.ehome.poct.core.application;

import cn.hutool.json.JSONUtil;
import com.ehome.poct.core.api.common.DeviceTypeConst;
import com.ehome.poct.core.api.dto.check.AlgoLocalDataDTO;
import com.ehome.poct.core.api.dto.check.AlgoNotifyDTO;
import com.ehome.poct.core.api.dto.check.CheckParamDTO;
import com.ehome.poct.core.api.vo.check.CellBoardValidVO;
import com.ehome.poct.core.api.vo.check.CheckProcessResultVO;
import com.ehome.poct.core.api.vo.check.CheckStatusVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 检测处理过程编排
 * (单机，金标仪单测，血常规单测，生化仪单测等等）
 *
 * @author cq
 * @since 2022/03/02 17:44
 **/
@Component
@RefreshScope
@RequiredArgsConstructor
public class StandaloneCheckExe {
    @Autowired private CheckFactory checkFactory;

    public CheckProcessResultVO processCheck(CheckParamDTO checkParamDto){
        return checkFactory.get(checkParamDto.getDeviceType()).handleCheck(checkParamDto,checkParamDto.getClinic(), checkParamDto.getDevice());
    }

    public CheckStatusVO manualGetStatus(Long id){
        //检测状态只有血常规有
        return checkFactory.get(DeviceTypeConst.BLOOD).manualGetStatus(id);
    }

    public CheckStatusVO pollGetStatus(Long id){
        //检测状态只有血常规有
        return checkFactory.get(DeviceTypeConst.BLOOD).pollGetStatus(id);
    }

    public void algoCallBack(AlgoNotifyDTO param) {
        final var rbcRateList = List.of("LARGE_RBC_RATE", "SMALL_RBC_RATE");
        final var resultsMap = param.getResults().stream()
                .collect(Collectors.groupingBy(it -> rbcRateList.contains(it.getType()) ? "morphology" : "base"));
        //检测状态只有血常规有
        final var errorList = List.of("WBC", "RBC", "PLT", "HGB");
        final var hasZero = param.getResults().stream()
                .anyMatch(it -> errorList.contains(it.getType()) && new BigDecimal(it.getValue()).signum() == 0);
        checkFactory.get(DeviceTypeConst.BLOOD).updateResult(param.getId(), param.getAnalyseMsg(),
                JSONUtil.toJsonStr(resultsMap.get("base")), JSONUtil.toJsonStr(resultsMap.get("morphology")), JSONUtil.toJsonStr(param.getCharts()), JSONUtil.toJsonStr(param.getImages()), hasZero);
    }

    public Boolean  boardIsExist(String sno)
    {
       return checkFactory.get(DeviceTypeConst.BLOOD).boardIsExist(sno);
    }

    public CellBoardValidVO boardThickness(String sno) {
       return checkFactory.get(DeviceTypeConst.BLOOD).boardThickness(sno);
    }

    /**
     * 血常规 本地化算法
     * @param algoDto
     * @return
     */
    public CheckProcessResultVO saveLocalAlgodata(AlgoLocalDataDTO algoDto){
        return checkFactory.get(DeviceTypeConst.BLOOD).saveLocalAlgodata(algoDto);
    }
}
